package light.head.controller.site;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.config.ConfigParm;
import light.head.config.RunStatus;
import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.sys.OrganSynopsisDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.model.FileInfo;
import light.head.model.OrganSynopsis;
import light.head.model.OrganSynopsisAnnex;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 *	企业简介
 */
@Controller
@RequestMapping(Url.ORGANSYNOPSIS)
public class OrganSynopsisController extends SupporterController{
	private OrganSynopsisDAO osDAO;
	private final static String upload_path = "upload/organSynopsisAnnex/";
	private final static String organdetail_photo_path = "upload/organSynopsisPhoto/";
	private final static String organdetail_file_path = "upload/organSynopsisFile/";
	
	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Integer code=cu_organCode(request);
		OrganSynopsis od=osDAO.get(code);
		if (null != od) {
//			request.setAttribute(Parm.ORGANDETAIL, od);
//			List<OrganSynopsisAnnex> list=osDAO.findAnnexByCode(code);
//			if(list!=null){
//				request.setAttribute(Parm.LIST, list);
//			}
		}
		return new ModelAndView(Url.ORGANSYNOPSIS_EDIT);
	}

	@RequestMapping(value = Url.SAVE)
	public void save(OrganSynopsis os, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		if (os.getCode() != null) {
			result = osDAO.upd(os);
		} else {
			os.setCt(new Date());
			os.setCu(cu_code(request));
			os.setOc(cu_organCode(request));
			result = osDAO.add(os);
		}
		if (result == RESULT.SUCCESS) {
			List<Object> noDelCodes = new ArrayList<Object>();
			if (null != os.getList() && os.getList().size() > 0) {
				for (OrganSynopsisAnnex osa : os.getList()) {
					noDelCodes.add(osa.getCode());
				}
			}
			String[] afcs = request.getParameterValues(Parm.AFCS);
			if (null != afcs && afcs.length > 0) {
				StringBuffer codes = new StringBuffer();
				for (String code : afcs) {
					codes.append(code + Sys.COMMA);
				}
				codes.deleteCharAt(codes.length() - 1);
				List<FileInfo> list = osDAO.findFileByCodes(codes.toString());
				if (null != list && list.size() > 0) {
					OrganSynopsisAnnex temp = null;
					for (FileInfo fi : list) {
						temp = new OrganSynopsisAnnex();
						temp.setExt(fi.getExt());
						temp.setOdc(os.getCode());
						temp.setName(fi.getName());
						temp.setSize(fi.getSize());
						temp.setSn(fi.getUuid());
						osDAO.add(temp);
						noDelCodes.add(temp.getCode());
					}
				}
			}
			osDAO.deleteAnnexNotInCodes(os.getCode(), noDelCodes);
			RunStatus.pcIndexCreateState = Sys.B_ZERO;
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
		}
	}
	
	
	// 单个文件保存
	@Transactional
	@RequestMapping(Url.UPLOAD)
	public void upload(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile pohto = multipartRequest.getFile(Parm.UPLOAD);
		String type = request.getParameter(Parm.TYPE);
		String name = pohto.getOriginalFilename();
		if (isNotNull(name)) {
			String ext = name.substring(name.lastIndexOf(Sys.DOT) + 1);
			if (!ext.toUpperCase().equals(Sys.JPG)
					&& !ext.toUpperCase().equals(Sys.GIF)
					&& !ext.toUpperCase().equals(Sys.JPEG)
					&& !ext.toUpperCase().equals(Sys.BMP)
					&& !ext.toUpperCase().equals(Sys.PNG)
					&& !ext.toUpperCase().equals(Sys.XLSX)
					&& !ext.toUpperCase().equals(Sys.XLS)
					&& !ext.toUpperCase().equals(Sys.DOCX)
					&& !ext.toUpperCase().equals(Sys.DOC)
					&& !ext.toUpperCase().equals(Sys.PDF)
					&& !ext.toUpperCase().equals(Sys.PPT)
					&& !ext.toUpperCase().equals(Sys.RAR)
					&& !ext.toUpperCase().equals(Sys.ZIP)) {
				print(response, Msg.J_FILE_TYPE_ERROR);
				return;
			}
			name = name.substring(0, name.lastIndexOf(Sys.DOT));

			UUID u = UUID.randomUUID();
			String uuid = u.toString().replace("-", "");
			String path = (type.equals(Sys.FILE) ? organdetail_file_path : organdetail_photo_path) + uuid + Sys.DOT + ext;
			String savePath = ConfigParm.getProjectPath() + path;
			FileOutputStream fo;
			int size = 0;
			try {
				fo = new FileOutputStream(savePath);
				size = pohto.getBytes().length;
				fo.write(pohto.getBytes());
				fo.close();
			} catch (Exception e) {
				print(response, Msg.J_ERROR);
				e.printStackTrace();
				throw new RuntimeException();
			}

			FileInfo f = new FileInfo();
			f.setDeleted(false);
			f.setExt(ext);
			f.setName(name);
			f.setUuid(uuid);
			f.setCt(new Date());
			if (type.equals(Sys.FILE)) {
				f.setType(Sys.B_ONE);
				f.setModule(Parm.ORGANSYNOPSISFILE);
			} else {
				f.setType(Sys.B_TWO);
				f.setModule(Parm.ORGANSYNOPSISPHOTO);
			}

			f.setCu(cu_code(request));
			f.setOc(cu_organCode(request));
			f.setSize(size);
			osDAO.add(f);

			StringBuffer result = new StringBuffer();
			result.append("<script type=\"text/javascript\">");
			if (isNotNull(path)) {
				result.append("window.parent.CKEDITOR.tools.callFunction("+ request.getParameter("CKEditorFuncNum") + ",'" + path + "',''" + ")");
				result.append("</script>");
				result.append(path);
			} else {
				result.append("alert(\"上传失败，文件类型需要jpg、gif或png\")");
				result.append("</script>");
			}
			response.setHeader("Content-Type", "text/html; charset=UTF-8");
			print(response, result.toString());

		} else {
			print(response, Msg.J_ERROR);
		}
	}

	// 上传多个文件
	@Transactional
	@RequestMapping(Url.UPLOADS)
	public void uploads(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		List<MultipartFile> files = multipartRequest.getFiles("files");
		StringBuffer result = new StringBuffer("");
		if (null != files && files.size() > 0) {
			String name = null;
			String ext = null;
			String uuid = null;
			String path = null;
			String savePath = null;
			UUID u = null;
			for (MultipartFile mf : files) {
				name = mf.getOriginalFilename();
				if (isNotNull(name)) {
					ext = name.substring(name.lastIndexOf('.') + 1);
					if (!ext.toUpperCase().equals(Sys.JPG) && !ext.toUpperCase().equals(Sys.GIF)
							&& !ext.toUpperCase().equals(Sys.JPEG) && !ext.toUpperCase().equals(Sys.BMP)
							&& !ext.toUpperCase().equals(Sys.PNG)  && !ext.toUpperCase().equals(Sys.XLSX)
							&& !ext.toUpperCase().equals(Sys.XLS)  && !ext.toUpperCase().equals(Sys.DOCX)
							&& !ext.toUpperCase().equals(Sys.DOC)  && !ext.toUpperCase().equals(Sys.PDF)
							&& !ext.toUpperCase().equals(Sys.PPT)  && !ext.toUpperCase().equals(Sys.RAR)
							&& !ext.toUpperCase().equals(Sys.ZIP)) {
						print(response, Msg.J_FILE_TYPE_ERROR);
						return;
					}
					name = name.substring(0, name.lastIndexOf('.'));
					u = UUID.randomUUID();
					uuid = u.toString().replace("-", "");
					path = upload_path + uuid + Sys.DOT + ext;
					savePath = ConfigParm.getProjectPath() + path;
					FileOutputStream fo;
					int size = 0;
					try {
						fo = new FileOutputStream(savePath);
						size = mf.getBytes().length;
						fo.write(mf.getBytes());
						fo.close();
					} catch (Exception e) {
						print(response, Msg.ERROR);
						e.printStackTrace();
					}

					FileInfo f = new FileInfo();
					f.setDeleted(false);
					f.setExt(ext);
					f.setName(name);
					f.setUuid(uuid);
					f.setCt(new Date());
					f.setType(isImg(ext) ? Sys.B_TWO : Sys.ONE);
					f.setModule(Parm.ORGANSYNOPSISANNEX);
					f.setCu(cu_code(request));
					f.setOc(cu_organCode(request));
					f.setSize(size);
					osDAO.add(f);
					result.append("{\"name\":\"" + name + "\",\"code\":\""+ f.getCode() + "\",\"ext\":\"" + ext+ "\",\"size\":\"" + size + "\",\"path\":\"" + uuid+ Sys.DOT + ext + "\"},");
				}
			}
			result.insert(0, "{\"result\":\"success\",\"list\":[").deleteCharAt(result.length() - 1).append("]}");
			print(response, result.toString());
		} else {
			result.append("{\"result\":\"not_find_file\"}");
		}
	}

	private boolean isImg(String ext) {
		if (!isNotNull(ext))
			return false;
		if (ext.toUpperCase().equals(Sys.JPG)
				|| ext.toUpperCase().equals(Sys.GIF)
				|| ext.toUpperCase().equals(Sys.JPEG)
				|| ext.toUpperCase().equals(Sys.BMP)
				|| ext.toUpperCase().equals(Sys.PNG)) {
			return true;
		}
		return false;
	}
	@Autowired
	public void setOsDAO(OrganSynopsisDAO osDAO) {
		this.osDAO = osDAO;
	}
}
